<template>
  <div class="login_container">
    <div>
      <setBar
        title="boyiChat"
        :show-stick="false"
        :show-reduce="false"
        :show-extend="false"
      ></setBar>
    </div>
    <div class="login">
      <div class="msg_error">{{ msgText }}</div>
      <!-- 表单 -->
      <el-form
        class="login_form"
        label-width="56px"
        label-position="left"
        :module="fromData"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="fromData.username"
            clearable
            placeholder="请输入用户名"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" label="邮箱">
          <el-input v-model="fromData.email" clearable placeholder="请输入邮箱">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="fromData.password"
            type="password"
            show-password
            clearable
            placeholder="请输入密码"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" label="复密码">
          <el-input
            v-model="fromData.repassword"
            type="password"
            show-password
            clearable
            placeholder="请在次输入密码"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" class="verify">
          <el-input
            v-model="fromData.verifyCode"
            placeholder="请输入验证码"
            class="verify_code"
            ><template #prefix>
              <el-icon><Promotion /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <!-- 验证码 -->
      <div class="verify">
        <sldentify
          ref="sldentifyRef"
          class="verify_img"
          width="150px"
          height="50px"
          @getValue="getValue"
        ></sldentify>
        <span @click="changeVerifyCode">看不清,换一个...</span>
      </div>
      <!-- 确定按钮 -->
      <div class="btn">
        <el-button
          type="primary"
          class="submit"
          :loading="loading"
          @click="submit"
          >{{ isLogin ? '登录' : '注册' }}</el-button
        >
      </div>
      <!-- 却换登录注册 -->
      <div class="tip" @click="changeLoginRegist">
        <span>去{{ loginRegistText }}...</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, useTemplateRef } from 'vue'

import { isEmpty, isVerify } from '@renderer/pages/Login/utils/verify'
import { loginApi, registerApi } from '@renderer/api'
import { message } from '@renderer/utlis/feedback'

import sldentify from '@renderer/components/sIdentify.vue'
import setBar from '@renderer/components/set-bar.vue'

import useUser from '@renderer/pinai/modules/user'

import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUser()

const fromData = ref({
  username: '',
  password: '',
  email: '',
  repassword: '',
  verifyCode: ''
}) // 表单数据
const verifyCode = ref('') // 验证码
const isLogin = ref(true) // 是否登录
const msgText = ref('') // 错误信息
const loading = ref(false) // 加载状态

const sldentifyRef =
  useTemplateRef<InstanceType<typeof sldentify>>('sldentifyRef') // 验证码组件实例

const loginRegistText = computed(() => {
  // 登录注册切换文本
  return isLogin.value ? '注册' : '登录'
})

// 切换验证码
const changeVerifyCode = () => {
  sldentifyRef.value?.generateCaptcha()
}
// 得到图形验证码
const getValue = (value: string) => {
  verifyCode.value = value
}
// 切换登录注册
const changeLoginRegist = () => {
  isLogin.value = !isLogin.value
  msgText.value = ''
  // 置空表单
  fromData.value = {
    username: '',
    password: '',
    email: '',
    repassword: '',
    verifyCode: ''
  }
  // 清空验证码
  // 向主进程通信切换窗口大小
  window.electron.ipcRenderer.send('changeWindowSize', {
    isLogin: isLogin.value,
    loginOrResgist: true
  })
  //改变验证码
  changeVerifyCode()
}
// 注册用户
const regist = async () => {
  loading.value = true
  try {
    const res: any = await registerApi(fromData.value)
    loading.value = false
    if (res?.code === 200) {
      // 注册成功
      changeLoginRegist()
      message('注册成功', 'success')
    }
  } catch (error: any) {
    loading.value = false
  }
}
// 用户登录
const login = async () => {
  loading.value = true
  try {
    const res: any = await loginApi(fromData.value)
    if (res?.code === 200) {
      loading.value = false
      // 保存个人信息
      userStore.setUserInfo(res.data)
      userStore.setToken(res.data.token)
      // 设置用户信息在主线程中
      window.electron.ipcRenderer.send('setUserInfo', res.data)
      message('登录成功', 'success')
      setTimeout(() => {
        router.push('/')
      })
    }
  } catch (error: any) {
    loading.value = false
  }
}
// 提交登录或注册
const submit = () => {
  msgText.value = ''
  // 验证表单是否为空
  const emptyRes = isEmpty(fromData.value, isLogin.value)
  // 验证表单正则是否通过
  const verifyRes = isVerify(fromData.value, isLogin.value)
  if (!emptyRes.status || !verifyRes.status) {
    return (msgText.value = emptyRes.message || verifyRes.message)
  }
  // 验证验证码
  if (verifyCode.value !== fromData.value.verifyCode) {
    return (msgText.value = '验证码错误')
  }
  // 登录与注册
  return isLogin.value ? login() : regist()
}
</script>

<style lang="scss" scoped>
.login_container {
  .login {
    width: 100vw;
    height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;

    .msg_error {
      height: 30px;
      /* margin-top: 10px; */
      color: #f56c6c;
    }

    .login_form {
      width: 260px;
      /* height: 140px; */
      margin-top: 20px;
    }

    .verify {
      color: #07c160;
      text-align: center;
      font-size: 12px;
      margin-top: 10px;
    }

    .btn {
      width: 80%;
      margin-top: 10px;
      .submit {
        width: 100%;
      }
    }

    .tip {
      color: #07c160;
      position: absolute;
      bottom: 10px;
      right: 50px;
      cursor: pointer;
    }
  }
}
</style>
